<template>
  <div class="boxs">
    <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
    >
      <el-form-item label="" prop="skuName">
        <el-input
            v-model="queryParams.skuName"
            placeholder="请输入券名称"
            clearable
            size="small"
        />
      </el-form-item>
      <el-form-item>
        <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="handleQuery"
        >搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-plus" type="primary"  size="small" @click="openDialog">添加券</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="list" style="margin-top: 15px" v-loading="loading">
      <el-table-column label="ID" align="center" min-width="60" prop="id" />
      <el-table-column label="券名称" align="center" min-width="120" prop="skuName" />
      <el-table-column label="封面图" align="center" min-width="100" prop="imgUrl">
        <template  slot-scope="scope">
          <img style="width:80px;height:80px;border:none;" :src="scope.row.imgUrl" v-if="scope.row.imgUrl">
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" min-width="100" prop="price" />
      <el-table-column label="划线价" align="center" min-width="100" prop="orinprice" />
      <el-table-column label="库存" align="center" min-width="100" prop="inventory" />
      <el-table-column label="状态" align="center" min-width="100" prop="state">
        <template  slot-scope="scope">
          <el-tag
            :type="scope.row.state==1?'success':'info'"
            effect="dark">
            {{ scope.row.state==1?'已上架':'已下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="所属分类" align="center" min-width="120" prop="type">
        <template slot-scope="scope">
          <el-tag
            v-for="item in scope.row.type.split(',')"
            :key="item"
            effect="plain" style="margin:3px">
            {{item==1?'现金专区':item==2?'中国移动话费专区':item==3?'热门推荐':''}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" :formatter="formatterCreateTime"  min-width="140"/>
      <el-table-column label="操作" align="center" >
        <template slot-scope="scope">
          <el-button size="mini"  @click="handleEdit(scope.row)"  type="primary">编辑</el-button>
          <!-- <el-button size="mini"  @click="del(scope.row.id)"  type="danger">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.size"
        @pagination="getCoupon"
    />

    <el-dialog title="券信息" :visible.sync="dialogVisible" width="50%" :close-on-click-modal="false">
      <el-form  class="demo-form-inline" label-width="100px" :model="form" :rules="rules" ref="ruleForm" :inline="true">
        <el-form-item label="券封面" prop="imgUrl"  style="width:100%">
          <el-upload
            id="upload" ref="upload" 
            accept=".png,.jpg"
            class="upload-demo"
            action="#" 
            list-type="picture" 
            :auto-upload="false" 
            :on-remove="handleRemove"
            :on-change="changeFile"
            :http-request="uploadFile"
            :on-success="handleSuccess"
            :multiple="true"
            :file-list="fileList"
            style="max-width:300px">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="券名称" prop="skuName" >
          <el-input v-model="form.skuName" placeholder="请输入券名称" style="width:220px"/>
        </el-form-item>
        <el-form-item label="券类型" prop="discountType">
          <el-select v-model="form.discountType" placeholder="请选择券类型" style="width:220px">
            <el-option
              v-for="item in discountTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="type" >
          <el-checkbox-group v-model="form.type">
            <el-checkbox label="1" key="1">现金专区</el-checkbox>
            <el-checkbox label="2" key="2">中国移动话费专区</el-checkbox>
            <el-checkbox label="3" key="3">热门推荐</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
         <el-form-item label="划线价" prop="orinprice" >
          <el-input v-model="form.orinprice" placeholder="请输入券划线价" oninput="value=value.replace(/[^0-9.]/g,'').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3').replace(/^0+(?=\d)/,'')"/>
        </el-form-item>
         <el-form-item label="销售价" prop="price">
          <el-input v-model="form.price" placeholder="请输入券销售价" oninput="value=value.replace(/[^0-9.]/g,'').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3').replace(/^0+(?=\d)/,'')"/>
        </el-form-item>
        <el-form-item label="库存" prop="inventory">
          <el-input v-model.number="form.inventory" placeholder="请输入券库存" />
        </el-form-item>
        <el-form-item label="是否上架" prop="state">
          <el-switch v-model="form.state" :active-value='1' :inactive-value='0'></el-switch>
        </el-form-item>
        <!-- <el-form-item label="券详情图" prop="imgDetails" style="width:100%">
          <el-upload
            id="upload2" ref="upload2" 
            accept=".png,.jpg"
            class="upload-demo"
            action="#" 
            list-type="picture-card"
            :auto-upload="false" 
            :on-remove="handleRemove2"
            :on-change="changeFile2"
            :http-request="uploadFile2"
            :on-success="handleSuccess2"
            :multiple="true"
            :file-list="fileList2"
            >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item> -->
        <el-form-item label="券说明" prop="detailJson" >
          <quill-editor
            v-model="form.detailJson"
            :options="editorOptions"
            @blur="onEditorBlur"
            style="width:400px;"
          />
          <!-- <el-input type="textarea" v-model="form.description" :rows="12"  style="width:300px;" ></el-input>           -->
        </el-form-item>
        <el-form-item label="话费购链接"  >
          <el-input v-model="form.ydurl" placeholder="请输入话费购链接" style="width:400px;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-loading="addLoading">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :type="form.id ? 'warning' : 'primary'" @click="affirm">{{
            form.id ? "确认修改" : "确认添加"
        }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="imgdialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import {getProduct,upProduct,addProduct,delProduct,upload} from "@/api/admin";
import {formatDate} from "@/utils";
// 导入组件和样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import OSS from 'ali-oss';
import ossClient from '@/utils/ossConfig'; // 引入配置文件

export default {
  name: "Coupon",
  components: { quillEditor },
  data(){
    return {
      discountTypes:[
        {
          label:'来伊份零食畅享盲盒兑换券',
          value:1,
        },
        {
          label:'来伊份零食精选盲盒兑换券',
          value:2,
        },
        {
          label:'来伊份十全大礼包兑换券',
          value:3,
        },
        {
          label:'5元现金券(无门槛)',
          value:4,
        },
        {
          label:'来伊份权益会员88折扣券',
          value:5,
        },
        {
          label:'来伊份20元满减券',
          value:6,
        },
        {
          label:'来伊份50元满减券',
          value:7
        },
        {
          label:'来伊份100元满减券',
          value:8
        },
        {
          label:'来伊份会员88折券',
          value:9
        },
        {
          label:'来伊份会员85折券',
          value:10
        },
        {
          label:'来伊份会员8折券',
          value:11
        },
        {
          label:'来伊份会员75折券',
          value:12
        },
        {
          label:'来伊份0.1元换购29元券',
          value:13
        },
        {
          label:'来伊份0.1元换购59元券',
          value:14
        },
        {
          label:'来伊份0.1元换购69元券',
          value:15
        },
        {
          label:'来伊份0.1元换购99元券',
          value:16
        },
      ],
      imgdialogVisible:false,
      dialogImageUrl:'',
        editorOptions: {
          modules: {
            toolbar: [
              ['bold', 'italic', 'underline', 'strike'],
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            ]
          },
          placeholder: '请输入券说明...',
          theme: 'snow'
      },
      serverUrl: process.env.VUE_APP_BASE_API,
      fileData:[],
      fileData2:[],
      fileList:[],
      fileList2:[],
      id: this.$store.getters.id,
      queryParams:{
        page:1,
        size:10,
        skuName:'',
        isCoupon:1,
      },
      total:0,
      loading:false,
      addLoading:false,
      list:[],
      dialogVisible:false,
      form:{},
      rules:{
        skuName:[
          { required: true, message: '请输入券名称', trigger: 'blur' },
        ],
        type:[{ required: true, message: '请选择分类', trigger: 'change' }],
        price:[
          { required: true, message: '请输入销售价', trigger: 'blur' },
        ],
        orinprice:[
          { required: true, message: '请输入划线价', trigger: 'blur' },
        ],
        inventory:[
          { required: true, message: '请输入库存', trigger: 'blur' },
          { validator: this.validateInteger, trigger: 'blur' }
        ],
        discountType:[
          { required: true, message: '请选择券类型', trigger: 'change' },
        ],
      },

      
    }
  },
  created() {
    this.getCoupon();
  },
  methods:{
    validateInteger(rule, value, callback) {
      if (value === 0 || Number.isInteger(value)) {
        callback(); // 验证通过
      } else {
        callback(new Error('请输入0或整数')); // 验证失败，显示错误信息
      }
    },
    changeFile(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
      this.fileList=fileList;
    },
    changeFile2(file, fileList) {
      this.fileList2=fileList;
    },
    handleRemove(file, fileList) {
        console.log(file, fileList);
        this.fileList = fileList
    },
    handleRemove2(file, fileList) {
        console.log(file, fileList);
        this.fileList2 = fileList
    },
    handlePreview(file) {
        console.log(file);
    },
    handleSuccess(response, file) {
       if(response.code==200){
         // 处理上传成功的逻辑
          console.log('上传成功', response, file);
          this.$message.success('上传成功！'); // 使用 Element UI 的消息提示
       }else{
         this.$message.error("上传失败")
       }
    },
    handleSuccess2(response, file) {
       if(response.code==200){
         // 处理上传成功的逻辑
          console.log('上传成功', response, file);
          this.$message.success('上传成功！'); // 使用 Element UI 的消息提示
       }else{
         this.$message.error("上传失败")
       }
    },
    async finish() {
      try {
          this.fileData = new FormData();
          this.$refs.upload.submit();
          let {data}=await upload(this.fileData);
          console.log(9999888,data)
          return data[0];
        }catch (e) {
          this.$message.error("上传失败！");
        }
    },
    async finish2() {
      try {
          this.fileData2 = new FormData();
          this.$refs.upload2.submit();
          console.log(111111,this.fileData2);
          console.log(222222,this.fileList2);
          let {data}=await upload(this.fileData2);
          console.log(454546,data);
          return data;
        }catch (e) {
          this.$message.error("上传失败！");
        }
    },
    
    uploadFile:function(file){
      this.fileData.append('file', file.file);
    },
    uploadFile2:function(file){
      this.fileData2.append('file', file.file);
    },
    


    del(id){
        this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await delProduct({id:id});
          this.getCoupon();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });

        }).catch(() => {
           
        });
      },
    openDialog () {
      this.resetForm();
      this.dialogVisible = true
    },
    resetForm () {
      this.form = {source:'来伊份',state:1,type:[]};
      this.fileList=[]
      this.fileList2=[]
      this.fileData=[]
      this.fileData2=[]
    },
    affirm(){
      this.$refs['ruleForm'].validate(async (valid) => {
        if (!valid) return;
        try {
          if(this.fileList.length==0){
            this.$message.error("请上传封面！");
            return;
          }else{
            console.log(111);
            console.log(!this.form.id);
            console.log(this.form.imgUrl=='');
            console.log(222);
            let imgUrl=await this.finish();
            if(imgUrl){
                this.form.imgUrl=imgUrl;
            }
          }

          // if(this.form.id){
          //   this.form.imgDetails=await this.finish2();
          //   console.log(1,this.form.imgDetails);
          //    console.log(2,this.fileData2);
          //    console.log(3,this.fileList2);
          //    let oldUrl=this.fileList2.filter(f => !f.raw ).map(obj => obj.url);
          //    this.form.imgDetails=oldUrl.concat(this.form.imgDetails);
          //    console.log(4,this.form.imgDetails);
          // }else{
          //   this.form.imgDetails=await this.finish2();
          // }
         
          this.addLoading=true;
          this.form.imgDetails=[]
          this.form.isCoupon=this.form.discountType>3?1:0;
          !this.form.id&& await addProduct(this.form);
          this.form.id&&  await upProduct(this.form);
          this.addLoading=false;
          this.$message.success(this.form.id?'修改成功！':'添加成功！');
          this.getCoupon();
          this.dialogVisible = false;
        }catch (e) {
          this.addLoading=false;
        }

      });
    },
    async getCoupon(){
      this.loading=true;
      let {data,total}=await getProduct(this.queryParams);
      this.loading=false;
      this.list=data;
      this.total=total;
    },
    handleQuery(){
      this.queryParams.page=1;
      this.getCoupon();
    },
    handleEdit(row){
      console.log(999,row.type);
      if(!Array.isArray(row.type)){
        row.type=row.type.split(',')
      }
      this.form={...row};
      this.fileList=[
        {
          name:this.form.imgUrl.replace('https://sx-manage.oss-cn-hangzhou.aliyuncs.com/images/','').split('-').pop(),
          url:this.form.imgUrl
        }
      ];
      this.fileList2=[]
      let _this=this;
      if(this.form.imgDetails){
        this.form.imgDetails.split(',').forEach(function(img) {
              _this.fileList2.push({
                name:img.replace('https://sx-manage.oss-cn-hangzhou.aliyuncs.com/images/','').split('-').pop(),
                url:img
              })
          });
      }
      
      console.log(555,this.fileList2);
      this.dialogVisible=true;
      this.$refs['ruleForm'].clearValidate(); 
    },
    formatterCreateTime(row){
      return formatDate(row.updateTime);
    }
  }
}
</script>

<style scoped>
  .ql-container {
    min-height: 300px;
  }
</style>
